<template>
    <Modal @on-ok="choose" class="set-roles"
            :title="`设置关联人员 -- ${this.$store.state.employee.selectedOrgStruct&&this.$store.state.employee.selectedOrgStruct.node.origin.dept}`"
            ok-text="保存"
            width="1200"
            v-model="show"
            :mask-closable="false"
            :transfer="false">
        <div style="display: inline-block;width: 800px">
            <Table height="500" border :columns="relative_employees_columns" :data="relative_employees_data"></Table>
            <!--<Page :total="employeeTbPage.total" :page-size="args.limit" :current="employeeTbPage.current" size="small" show-elevator show-sizer @on-change="pageIndexChange" @on-page-size-change="pageSizeChange"></Page>-->
        </div>
        <div style="display: inline-block;margin-left:30px;width: 260px;vertical-align: top">
            <Input v-model="args.search.userName" @keyup.up.native.prevent="up" @keyup.down.native.prevent="down" clearable autofocus placeholder="用户名/账户搜索"></Input>
            <ul ref="ulList" style="margin-top: 10px;max-height: 458px;overflow-y: scroll;border: 1px solid #ccc;">
                <li ref="searchResult" title="双击添加" @keyup.up.native="up" @keyup.down.native="down" @click="selIndex=index" @dblclick="addToLeft(index,item)" @keyup.enter.native.prevent="addToLeft(index, item)"
                    class="aa" :class="{aaa: selIndex===index}" v-for="(item,index) in searchTb.filter(item1 => !args.search.userName||item1.label.indexOf(args.search.userName)>-1&&!relative_employees_data.find(item2 => item2.userName===item1.key))" :key="item.key" style="border-bottom: 1px solid #ccc;text-align: center;">
                    <span style="text-align:left;display:inline-block;width: 190px;padding: 0 10px">{{item.label}}</span>
                    <span style="display:inline-block;width: 40px;border-left: 1px solid #ccc"><Button type="text" @click="addToLeft(index,item)" icon="plus"></Button></span>
                </li>
            </ul>
        </div>
    </Modal>
</template>

<script>
    import Vue from 'vue'
    import * as employeeOpr from '../../http/employee.api'
    import moment from 'moment'

    export default {
        name: "SetRelativeEmployee",
        data() {
            return {
                employeeStatusOpts: [
                    {label: '正常', val: 'normal'},
                    {label: '禁用', val: 'forbidden'},
                    {label: '离职', val: 'disable'}
                ],
                employeeTbPage: {
                    current: 1,
                    total: 200,
                },
                searchTb: [],
                args: { // 员工列表参数
                    search: {
                        userName: undefined,     //用户名
                        // employeeName: undefined, // 员工姓名
                        // status: undefined,       //员工状态
                        orgStructId: undefined,  //组织架构id
                    },
                    pageReqired: true,    // 分页 true 是 false 否
                    limit: 20,            // 每页数目
                    offset: 0,            // 偏移量
                    sort: 'createTime',   // 排序的字段
                    order: 'desc',        // asc 升序 desc 降序
                },
                employeeTbSelection: [],
                relative_employees_columns: [
                    {
                        title: '用户名',
                        key: 'userName',
                        width: 100,
                        fixed: 'left',
                        sortable: true
                    }, {
                        title: '员工姓名',
                        key: 'employeeName',
                        width: 140
                    }, {
                        title: '性别',
                        key: 'gender',
                        width: 75,
                        render: function (h, {row, index, column}) {
                            const _self = this;
                            return h('span',{},[row[column.key]&&'男'||'女']);
                        }.bind(this),
                    }, {
                        title: '部门',
                        key: 'deptName',
                        width: 100
                    }, {
                        title: '职能',
                        key: 'duty',
                        width: 150
                    }, {
                        title: '状态',
                        key: 'status',
                        width: 75,
                        render: function (h, {row, index, column}) {
                            const _self = this;
                            let node = _self.employeeStatusOpts.find(item => item.val===row[column.key]);
                            return h('span',{style:{color: (row[column.key]==='normal')&&'#008000'||(row[column.key]==='forbidden')&&'#FF0000'}},[node&&node.label||'']);
                        }.bind(this),
                    }, {
                        title: '联系方式',
                        key: 'contact',
                        width: 125
                    }, {
                        title: '腾讯通',
                        key: 'rtx',
                        width: 100
                    }, {
                        title: '邮箱',
                        key: 'email',
                        width: 100
                    }, {
                        title: '创建时间',
                        key: 'createTime',
                        width: 100,
                        render: (h, {row, index, column}) => h('span',{},[(row[column.key]&&moment(row[column.key]).format('YYYY-MM-DDTHH:mm:ss')||'')]),
                    }, {
                        title: '操作',
                        fixed: 'right',
                        width: 65,
                        render: (h, {row, index, column}) => {
                            const _this = this;
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        icon: 'minus'
                                    },
                                    on: { // 编辑用户
                                        click: function () {
                                            _this.relative_employees_data.splice(index, 1)
                                        }
                                    }
                                })
                            ]);
                        }
                    }
                ],
                relative_employees_data: [],

                selIndex: -1
            }
        },
        computed: {
            show: {// 控制当前模块显示关闭
                get() {
                    return this.$store.state.employee.showRelativeEmployeeModal
                },
                set(value) {
                    this.$store.commit('employee/toggleRelativeEmployeeModal', value)
                }
            },

        },
        watch: {
            show: function (newVal, oldVal) {
                if (newVal) {
                    const _this  = this;
                    // 初始化组织架构树
                    let args = Object.assign({}, _this.args)
                    let struct = _this.$store.state.employee.selectedOrgStruct
                    if (struct&&struct.node.origin.id) {
                        // args.search.orgStructId = struct.node.origin.id;// 这是浅拷贝有问题 目前不支持 ... 展开复制
                        args.search = Object.assign({}, {orgStructId: struct.node.origin.id})
                    }
                    _this.getList(args).then(function (res) {
                        _this.relative_employees_data = res.data&&res.data.rows||[];
                    }).catch(function (err) {
                        console.log(err);
                    });

                    _this.getEmployeeNames()
                }
            }
        },
        mounted() {
            const _this = this;
            _this.$watch('args.search.userName', function (newVal, oldVal) {
                if (!newVal) {
                    _this.getEmployeeNames()
                    _this.selIndex = -1
                }
            })
        },
        created() {
            // console.log('created');
        },
        methods: {

            choose() { // 模态框确定
                const _this  = this;
                _this.$emit('employeeSelected', _this.relative_employees_data);
            },
            addToLeft(index, item) {
                const _this = this;
                // 去重复 判断
                if (_this.relative_employees_data.find(item2 => item2.userName===item.key)) {
                    return _this.$Message.warning('当前人员已存在，无需添加');
                }
                _this.getList({search:{userName: item.key}}).then(function (res) {
                    if (res.data.rows&&res.data.rows.length) {
                        if (res.data.rows[0].orgStruct) {
                            _this.$Modal.confirm({
                                title: '确认添加',
                                content: `当前人员是 ${res.data.rows[0].orgStruct.dept} 成员，确定将其移动到 ${_this.$store.state.employee.selectedOrgStruct.node.origin.dept} `,
                                onOk: () => {
                                    _this.searchTb.splice(index, 1)
                                    _this.relative_employees_data.push(res.data.rows[0])
                                }
                            })
                        } else {
                            _this.searchTb.splice(index, 1)
                            _this.relative_employees_data.push(res.data.rows[0])
                        }
                    } else {
                        console.log(`查不到 ${item.key} 用户信息添加失败`, res);
                    }
                }).catch(function (err) {
                    console.log(err);
                });

                // 设置分页信息
                // _this.employeeTbPage.total = _this.relative_employees_data.length;
            },
            getList(args) {
                return employeeOpr.getEmployees(args).then(function (res) {
                    res.data && res.data.rows && res.data.rows.map(item => {
                        item.genderDesc = item.gender && '男' || '女'
                        // 关联角色
                        item.roleNames = item.roles && item.roles.map(role => role.roleName).join(',');
                        // 职能
                        item.duty = item.orgFuncs && item.orgFuncs.map(duty => duty.funcName).join(',');
                        // 部门
                        item.deptName = item.orgStruct && item.orgStruct.dept
                    });
                    return Promise.resolve(res);
                })
            },
            /*pageIndexChange(index) {
                this.args.offset = this.args.limit * (index - 1);
                this.employeeTbPage.current = index;
                // this.getEmployees();
            },*/
            /*pageSizeChange(size) {
                this.args.limit = size;
                this.args.offset = 0;
                this.employeeTbPage.current = 1; // 此时改变当前页会触发 pageIndexChange 查询
                // this.getEmployees();
            },*/
            getEmployeeNames(args) {
                const _this = this;
                employeeOpr.getEmployeeNames(args).then(function (res) {
                    const data = res.data.result;
                    _this.searchTb = Object.keys(data).map(key => ({key, label: `${key}-${data[key]||''}`}));
                }).catch(function (err) {
                    console.log(err)
                })
            },
            up(event) {
                this.selIndex = (this.$refs.searchResult.length+this.selIndex-1)%(this.$refs.searchResult.length)
            },
            down(event) {
                this.selIndex = (this.selIndex+1)%(this.$refs.searchResult.length)
            }
        }
     }
</script>

<style scoped>
    .aaa, .aa:hover, .aaa:focus {
        background: #eee;
    }
</style>